const Koa = require('koa');
const app = new Koa();

// 路由中间件
// const route = require('koa-route');

// 静态资源的路由中间件
// const path = require('path');
// const serve = require('koa-static');

// const koaBody = require('koa-body');

// raw-body
// const getRawBody = require('raw-body');
// var contentType = require('content-type');

var formidable = require('formidable');


const funaaabbb = async (ctx, next) => {
  var form = new formidable.IncomingForm(); 
  form.parse(ctx.req, function(err, fields, files) {
    console.log({fields: fields, files: files});

    return ctx.body = '11111111';
    // res.writeHead(200, {'content-type': 'text/plain'});
    // res.write('received upload:\n\n');
    // res.end(util.inspect({fields: fields, files: files}));
  });
};
app.use(funaaabbb);



const funaaa = async (ctx, next) => {
  
  var form = new formidable.IncomingForm(); 
  var post = {},
       fileArray = [];
  form.uploadDir = './tmp';  //文件上传 临时文件存放路径 

  form
    .on('error', function(err) {
        console.log(err); //各种错误
    })
     //POST 普通数据 不包含文件 field 表单name value 表单value 
    .on('field', function(field, value) { 
        if (form.type == 'multipart') {  //有文件上传时 enctype="multipart/form-data" 
            if (field in post) { //同名表单 checkbox 返回array 同get处理
                if (util.isArray(post[field]) === false) {
                    post[field] = [post[field]];
                }
                post[field].push(value);
                return;
            }
        }
        post[field] = value;
    })
    .on('file', function(field, file) { //上传文件
      // console.log(field);
      // console.log(file);
        fileArray.push(file);
    });
  // await 
  // form.on('end', function() {
  //     // console.log(fileArray);
  //     // console.log(post);
  
  //   console.log('---- end return ----');

  //   // return ctx.body = 'hello koa22';
  //   // return next();// ctx.body = 'hello koa22';
  //   let aa = next();
  //   console.log(aa);
  //   ctx.body = aa;
  // });
  form.parse(ctx.req); //解析request对象
  
  await new Promise(function(resolve, reject){
    
    form.on('end', function(){
      resolve(next());
    });
  }).then(function(data){
    console.log(data);
    return ctx.body = data;
  });

  // form.parse(ctx.req); //解析request对象

  console.log('---- return ----');
  // return ctx.body = 'hello koa22';
  // next();
  
 

};
// app.use(funaaa);


const main = (ctx, next) => {
  next();
  console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);
  return ctx.body = 'hello koa22';
};
app.use(main);


app.listen(80);
console.log('server listening at 80');









